<template>
  <div class="inventory-container">
    <div class="coffee-bg"></div>
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i>添加商品
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品"
        style="width: 200px; margin-left: 16px">
        <template slot="prefix">
          <i class="el-icon-search"></i>
        </template>
      </el-input>
      <el-select v-model="categoryFilter" placeholder="商品类别" style="width: 120px; margin-left: 16px">
        <el-option label="全部" value="" />
        <el-option label="咖啡豆" value="咖啡豆" />
        <el-option label="牛奶" value="牛奶" />
        <el-option label="糖浆" value="糖浆" />
        <el-option label="杯具" value="杯具" />
      </el-select>
      <el-button type="success" icon="el-icon-download" @click="exportInventory" style="margin-left:16px">导出Excel</el-button>
    </div>

    <el-table :data="filteredInventory" style="width: 100%; margin-top: 20px" class="coffee-table">
      <el-table-column prop="id" label="商品编号" width="100" />
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="category" label="类别" />
      <el-table-column prop="currentStock" label="当前库存" />
      <el-table-column prop="minStock" label="最低库存" />
      <el-table-column prop="unit" label="单位" />
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag :type="getStockStatusType(scope.row)" :class="getStockStatus(scope.row) === '库存充足' ? 'coffee-tag' : ''">
            {{ getStockStatus(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template slot-scope="scope">
          <div class="action-buttons">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="primary" @click="handleRestock(scope.row)">补货</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      width="500px"
      class="coffee-dialog"
    >
      <el-form :model="inventoryForm" label-width="100px" :rules="rules" ref="inventoryFormRef">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="inventoryForm.name" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="inventoryForm.category">
            <el-option label="咖啡豆" value="咖啡豆" />
            <el-option label="牛奶" value="牛奶" />
            <el-option label="糖浆" value="糖浆" />
            <el-option label="杯具" value="杯具" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存" prop="currentStock">
          <el-input-number v-model="inventoryForm.currentStock" :min="0" />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input-number v-model="inventoryForm.minStock" :min="0" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="inventoryForm.unit" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </el-dialog>

    <!-- 补货对话框 -->
    <el-dialog
      :visible.sync="restockDialogVisible"
      title="补货"
      width="500px"
      class="coffee-dialog"
    >
      <el-form :model="restockForm" :rules="restockRules" ref="restockFormRef" label-width="100px">
        <el-form-item label="补货数量" prop="quantity">
          <el-input-number v-model="restockForm.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input
            v-model="restockForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入补货备注信息"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="restockDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRestockSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  data() {
    return {
      searchQuery: '',
      categoryFilter: '',
      dialogVisible: false,
      restockDialogVisible: false,
      dialogType: 'add',
      inventoryForm: {
        name: '',
        category: '',
        currentStock: 0,
        minStock: 0,
        unit: ''
      },
      restockForm: {
        quantity: 1,
        note: ''
      },
      inventory: [],
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择商品类别', trigger: 'change' }
        ],
        currentStock: [
          { required: true, message: '请输入当前库存', trigger: 'blur' },
          { type: 'number', message: '当前库存必须是数字', trigger: 'blur' }
        ],
        minStock: [
          { required: true, message: '请输入最低库存', trigger: 'blur' },
          { type: 'number', message: '最低库存必须是数字', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ]
      },
      restockRules: {
        quantity: [
          { required: true, message: '请输入补货数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '补货数量必须大于0', trigger: 'blur' }
        ],
        note: [
          { required: true, message: '请输入备注', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    filteredInventory() {
      return this.inventory.filter(item => {
        const matchSearch = item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
        const matchCategory = !this.categoryFilter || item.category === this.categoryFilter
        return matchSearch && matchCategory
      })
    }
  },
  created() {
    this.loadInventory()
  },
  methods: {
    loadInventory() {
      const local = localStorage.getItem('inventory')
      if (local) {
        this.inventory = JSON.parse(local)
      }
    },
    getStockStatus(item) {
      if (item.currentStock <= 0) return '缺货'
      if (item.currentStock <= item.minStock) return '库存不足'
      return '库存充足'
    },
    getStockStatusType(item) {
      if (item.currentStock <= 0) return 'danger'
      if (item.currentStock <= item.minStock) return 'warning'
      return 'success'
    },
    handleAdd() {
      this.dialogType = 'add'
      this.inventoryForm = { name: '', category: '', currentStock: 0, minStock: 0, unit: '' }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.inventoryForm = { ...row }
      this.dialogVisible = true
    },
    handleRestock(row) {
      this.restockForm = { quantity: 1, note: '' }
      this.restockDialogVisible = true
    },
    handleSubmit() {
      this.$refs.inventoryFormRef.validate(valid => {
        if (!valid) return
        if (this.dialogType === 'add') {
          const newItem = { ...this.inventoryForm, id: `INV${String(this.inventory.length + 1).padStart(3, '0')}` }
          this.inventory.push(newItem)
          this.$message.success('添加成功')
          this.addOperationLog('新增库存', `商品编号:${newItem.id} 名称:${newItem.name}`)
        } else {
          const index = this.inventory.findIndex(item => item.id === this.inventoryForm.id)
          this.inventory.splice(index, 1, { ...this.inventoryForm })
          this.$message.success('更新成功')
          this.addOperationLog('编辑库存', `商品编号:${this.inventoryForm.id} 名称:${this.inventoryForm.name}`)
        }
        localStorage.setItem('inventory', JSON.stringify(this.inventory))
        this.dialogVisible = false
      })
    },
    handleRestockSubmit() {
      this.$refs.restockFormRef.validate(valid => {
        if (!valid) return
        // 找到商品并增加库存
        const index = this.inventory.findIndex(item => item.id === this.inventoryForm.id)
        if (index !== -1) {
          this.inventory[index].currentStock += this.restockForm.quantity
        }
        localStorage.setItem('inventory', JSON.stringify(this.inventory))
        this.$message.success('补货成功')
        this.addOperationLog('补货', `商品编号:${this.inventoryForm.id || ''} 名称:${this.inventoryForm.name || ''} 补货数量:${this.restockForm.quantity}`)
        this.restockDialogVisible = false
      })
    },
    exportInventory() {
      const data = this.filteredInventory.map(item => ({
        商品编号: item.id,
        商品名称: item.name,
        类别: item.category,
        当前库存: item.currentStock,
        最低库存: item.minStock,
        单位: item.unit
      }))
      const ws = XLSX.utils.json_to_sheet(data)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '库存')
      XLSX.writeFile(wb, '库存数据.xlsx')
      this.addOperationLog('导出库存', `导出${data.length}条库存`)
    },
    addOperationLog(action, detail) {
      const user = JSON.parse(localStorage.getItem('adminUser') || '{}')
      const logs = JSON.parse(localStorage.getItem('operationLogs') || '[]')
      logs.push({
        time: new Date().toLocaleString(),
        user: user.username || '未知',
        action,
        detail
      })
      localStorage.setItem('operationLogs', JSON.stringify(logs))
    },
    handleDelete(row) {
      this.$confirm('确定要删除这个库存项吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.inventory = this.inventory.filter(item => item.id !== row.id)
        localStorage.setItem('inventory', JSON.stringify(this.inventory))
        this.$message.success('删除成功')
        this.addOperationLog('删除库存', `商品编号:${row.id} 名称:${row.name}`)
      }).catch(() => {
        // 用户点击取消按钮时，不执行任何操作
      })
    }
  }
}
</script>

<style scoped>
.inventory-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #e7d2ba 0%, #b08968 100%);
  position: relative;
  overflow: hidden;
}
.coffee-bg {
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  z-index: 0;
  pointer-events: none;
  background: url('https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/2615.png') repeat 0 0/120px auto;
  opacity: 0.06;
}
.header-actions {
  display: flex;
  align-items: center;
  z-index: 1;
}
.el-button--primary {
  background: linear-gradient(90deg, #a47149 0%, #7c4f22 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(124, 79, 34, 0.08);
  transition: background 0.2s;
}
.el-button--primary:hover {
  background: linear-gradient(90deg, #7c4f22 0%, #a47149 100%);
}
.el-button--success {
  background: linear-gradient(90deg, #b08968 0%, #a47149 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  border-radius: 8px;
}
.el-input__inner {
  background: #f8f5f2;
  border-radius: 8px;
  border: 1px solid #e0c3a0;
}
.el-select .el-input__inner {
  background: #f8f5f2;
  border-radius: 8px;
  border: 1px solid #e0c3a0;
}
.coffee-table {
  background: rgba(255,255,255,0.96);
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(124, 79, 34, 0.08);
  overflow: hidden;
}
.coffee-table th, .coffee-table td {
  background: transparent !important;
}
.coffee-tag {
  background: #e7d2ba !important;
  color: #7c4f22 !important;
  border: none !important;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}
.el-button--mini {
  padding: 7px 12px;
  border-radius: 6px;
}
.coffee-dialog .el-dialog {
  border-radius: 16px;
  box-shadow: 0 4px 18px 0 rgba(124, 79, 34, 0.10);
  border: 1px solid #e0c3a0;
  background: rgba(255, 255, 255, 0.98);
}
</style> 